# 系统相关
import os
import time
import logging

# flask相关
from flask import Flask, render_template, current_app
from werkzeug.contrib.fixers import ProxyFix
from flask_cors import CORS

# 和业务有关的模块
from hzb.config import BaseConfig
from hzb.auth import auth
from hzb.common import common
from hzb.users import users
from hzb.label import label


def set_log_config(app, level=BaseConfig.LOG_LEVEL):
    # log配置，实现日志自动按日期生成日志文件
    def make_dir(make_dir_path):
        path = make_dir_path.strip()
        if not os.path.exists(path):
            print(os.path.abspath(path))
            os.makedirs(path)
        return path

    # 与运行目录同一级
    print(os.path.abspath(__file__))
    _path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    log_dir_name = os.path.join(_path, "logs")
    log_file_name = 'logger-' + time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
    log_file_folder = log_dir_name
    make_dir(log_file_folder)
    log_file_str = log_file_folder + os.sep + log_file_name
    log_level = level

    handler = logging.FileHandler(log_file_str, encoding='UTF-8')
    handler.setLevel(log_level)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s行 - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)


# App中不允许使用print了
def create_app(db, new_config=BaseConfig):
    app = Flask(__name__)
    # 允许全部跨域
    CORS(app)
    db.init_app(app)
    app.config.from_object(new_config)
    # 图片路径
    app.add_url_rule('/image/<path:filename>',
                     endpoint='image',
                     view_func=app.send_static_file)
    # 蓝图注册
    register_blueprints(app)
    # log事件注册
    set_log_config(app, level=new_config.LOG_LEVEL)

    # @app.before_request
    # def before_request():
    #     g.request_start_time = time.time()
    #     g.request_time = lambda: '%.5fs' % (time.time() - g.request_start_time)

    # @app.route('/', methods=['GET'])
    # def index():
    #     return render_template('pc.html')

    # 日志中记录错误
    @app.errorhandler(500)
    def internal_server_error(e):
        app.logger.exception('error 500: %s', e)
        return 'internal server error', 500

    @app.route('/admin', methods=['GET'])
    def admin():
        return render_template('admin.html')

    @app.route('/app', methods=['GET'])
    def pc():
        return render_template('app.html')

    @app.route('/test', methods=['GET'])
    def test():
        return 'hello world'

    return app


def register_blueprints(app):
    # 模块后带版本号
    app.register_blueprint(users, url_prefix='/users')
    app.register_blueprint(label, url_prefix='/label')
